package cn.ibizlab.odoo.activiti.service.impl;

import cn.ibizlab.odoo.activiti.service.IProcessService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;


@Service
public class ProcessServiceImpl implements IProcessService {

	@Autowired
	RepositoryService repositoryService;

	@Autowired
	RuntimeService runtimeService;

	/**
	 * 
	 * 功能描述:classpath部署流程
	 *
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public String deployWF( String resourceFilePath) {

		String deployId="";

		try {
			// 创建一个部署对象
			Deployment deploy = repositoryService.createDeployment()
					.addClasspathResource("processes/" + resourceFilePath).deploy();

			deployId=deploy.getId();
			System.out.println("部署成功:" + deploy.getId());
			System.out.println("*****************************************************************************");
		} catch (Exception e) {
			return deployId;
		}
		return deployId;
	}

	/**
	 * 
	 * 功能描述:删除流程定义
	 *
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public String deDeployWF(String deployId) {

		try {
//			// 不带级联的删除：只能删除没有启动的流程，如果流程启动，则抛出异常
//			repositoryService.deleteDeployment(deploymentId);
			// 能级联的删除：能删除启动的流程，会删除和当前规则相关的所有信息，正在执行的信息，也包括历史信息
			repositoryService.deleteDeployment(deployId, true);
			System.out.println("删除成功:" + deployId);
			System.out.println("*****************************************************************************");
		} catch (Exception e) {
			return "fail";
		}
		return "success";
	}

	/**
	 * 
	 * 功能描述:启动流程
	 *
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public String startWF(String processId, Map variables) {

		try {

			ProcessInstance instance = runtimeService.startProcessInstanceByKey(processId, variables);
//			// Businesskey:业务标识，通常为业务表的主键，业务标识和流程实例一一对应。业务标识来源于业务系统。存储业务标识就是根据业务标识来关联查询业务系统的数据
//			ProcessInstance instance = runtimeService.startProcessInstanceByKey(processDefinitionKey, businessKey,
//					variables);

			System.out.println("流程实例ID:" + instance.getId());
			System.out.println("流程定义ID:" + instance.getProcessDefinitionId());
			System.out.println("*****************************************************************************");
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
		return "success";
	}

	/**
	 * 
	 * 功能描述:删除流程
	 *
	 * @see [相关类/方法](可选)
	 * @since [产品/模块版本](可选)
	 */
	public String deleteWF(String instanceId) {

		try {
			runtimeService.deleteProcessInstance(instanceId, "流程已完毕");
			System.out.println("终止流程");
			System.out.println("*****************************************************************************");
		} catch (Exception e) {
			return "fail";
		}
		return "success";
	}

}
